﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace Chant
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        DispatcherTimer _timer = new DispatcherTimer();
        string _currentSource = null;

        public bool IsAutoRewind
        {
            get { return App.AppSettings.IsAutoRewind;}
            set
            {
                if (App.AppSettings.IsAutoRewind != value)
                {
                    App.AppSettings.IsAutoRewind = value;
                    OnPropertyChanged("IsAutoRewind");

                    App.SaveSettings();
                }
            }
        }

        public MainPage()
        {
            this.InitializeComponent();

            SettingsPane.GetForCurrentView().CommandsRequested += MainPage_CommandsRequested;

            this.mediaPlayer.MediaOpened += mediaPlayer_MediaOpened;
            this.mediaPlayer.MediaEnded += mediaPlayer_MediaEnded;
            this.mediaPlayer.CurrentStateChanged += mediaPlayer_CurrentStateChanged;

            _timer.Interval = new TimeSpan(0, 0, 1);
            _timer.Tick += timer_Tick;

            EnableButtons(false, false, false);
        }

        bool _notFired = false;


        void mediaPlayer_CurrentStateChanged(object sender, RoutedEventArgs e)
        {
            bool enablePlayButton = false;
            bool enablePauseButton = false;
            bool enableStopButton = false;

            MediaElementState currentState = MediaElementState.Closed;

            try
            {
                currentState = this.mediaPlayer.CurrentState;
            }
            catch { }

            switch (currentState)
            {
                case MediaElementState.Buffering:
                    enableStopButton = true;
                    break;

                case MediaElementState.Closed:
                    break;

                case MediaElementState.Opening:
                    enableStopButton = true;
                    break;

                case MediaElementState.Paused:
                    enablePlayButton = true;
                    break;

                case MediaElementState.Playing:
                    enableStopButton = true;
                    enablePauseButton = true;
                    break;

                case MediaElementState.Stopped:
                    enablePlayButton = true;
                    break;
            }

            EnableButtons(enablePlayButton, enablePauseButton, enableStopButton);
        }

        private void EnableButtons(bool enablePlayButton, bool enablePauseButton, bool enableStopButton)
        {
            this.btnPlay.IsEnabled = enablePlayButton;
            this.btnPause.IsEnabled = enablePauseButton;
            this.btnStop.IsEnabled = enableStopButton;

            if (string.IsNullOrEmpty(_currentSource) == true)
            {
                this.btnPlay.IsEnabled = false;
            }
        }

        void timer_Tick(object sender, object e)
        {
            try
            {
                _notFired = true;

                if (this.mediaPlayer.CurrentState != MediaElementState.Playing)
                {
                    return;
                }

                this.sliderProgress.Value = this.mediaPlayer.Position.TotalSeconds;
            }
            finally
            {
                _notFired = false;
            }
        }

        void mediaPlayer_MediaOpened(object sender, RoutedEventArgs e)
        {
            this.sliderProgress.Maximum = this.mediaPlayer.NaturalDuration.TimeSpan.TotalSeconds;
            _timer.Start();
        }
        void mediaPlayer_MediaEnded(object sender, RoutedEventArgs e)
        {
            _timer.Stop();
        }

        async void MainPage_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            var privacyStatement = new SettingsCommand("privacy", "Privacy Statement", x => Launcher.LaunchUriAsync(
                    new Uri("http://www.sysnet.pe.kr/2/0/1649")));

            args.Request.ApplicationCommands.Clear();
            args.Request.ApplicationCommands.Add(privacyStatement);
        }

        private void SeekToMediaPosition(object sender, RangeBaseValueChangedEventArgs args)
        {
            if (_notFired == true)
            {
                return;
            }

            int SliderValue = (int)this.sliderProgress.Value;

            TimeSpan ts = new TimeSpan(0, 0, 0, SliderValue);
            this.mediaPlayer.Position = ts;
        }


        private void btnPlay_Click(object sender, RoutedEventArgs e)
        {
            this.mediaPlayer.Play();
        }

        private void btnPause_Click(object sender, RoutedEventArgs e)
        {
            this.mediaPlayer.Pause();
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            this.mediaPlayer.Stop();
        }

        private void PlayChant(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            string fileName = btn.Tag as string;

            if (string.IsNullOrEmpty(fileName) == true)
            {
                return;
            }

            mediaPlayer.IsLooping = this.chkAutoRewind.IsChecked ?? false;

            mediaUrl.Text = fileName;
            _currentSource = "ms-appx:///res/" + fileName;
            this.mediaPlayer.Source = new Uri(_currentSource);
        }
    }
}
